// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
const MJCardData = require("MJCardData");
const MJTool = require('MJCommon');
const CardSpriteType = MJTool.CardSpriteType;
const GameFace = require("GameFace");
const TVKey = require('ToolUtil').TVKey;
const tool = require('ToolUtil');
const NetManager = tool.NetManager();
const TABLESTATE = tool.TABLESTATE;
const ACTION = require("MJCommon").MJAction;

cc.Class({
    extends: cc.Component,
    mMjCardLayer: null, //临时精灵层
    properties: {
        BG: cc.Sprite,
        MJTexturePlist: cc.SpriteAtlas,
        Color: cc.Node,
        MJSprite: cc.Prefab,
        cardHu: cc.SpriteFrame,
        cardHaidi: cc.SpriteFrame,
        gameFace: {
            default: [],
            type: [GameFace]
        },
        MJCARD: {
            default: [],
            type: [MJCardData]
        },
        boxEat: {
            default: [],
            type: cc.Node
        },
        chiSprArr: {
            default: [],
            type: [cc.SpriteFrame]
        },
        pengSprArr: {
            default: [],
            type: [cc.SpriteFrame]
        },
        gangSprArr: {
            default: [],
            type: [cc.SpriteFrame]
        },
        buSprArr: {
            default: [],
            type: [cc.SpriteFrame]
        },
        arrowSpr: cc.SpriteFrame,
        cardSelect: cc.Node,
        cpgBar: cc.Node,
        waitNode: cc.Node,
        ruleLable: cc.Label,
        roomLable: cc.Label,
        gameSprite: cc.Sprite,
        btnChi: cc.Sprite,
        btnPeng: cc.Sprite,
        btnGang: cc.Sprite,
        btnBu: cc.Sprite,
        btnHu: cc.Sprite,
        btnZimo: cc.Sprite,
        btnCancel: cc.Sprite,
        btnReady: cc.Button,
        btnExit: cc.Button,
        balance: cc.Node,
        _gameConfig: null,
        _roomID: null,
        _makerID: null,
        _matchID: null,
        _bankerID: null, //庄的ID
        _tableState: 0, //桌子状态
        _gangPlayer: null, //刚开杠的玩家
        _curPlayer: null, //当前的玩家
        _lastPlayer: null, //上一个动作的玩家
        _lastOutCard: null, //刚出的牌 
        _packetload: false,
        _lastOutCardSprite: null, //上一次刚打出来的精灵
        _lastOutCardSprite2: null,
        _selectCard: null,
        _selectIdx: -1,
        _hutype: null, //吃碰杠bar的类型
        _packetID: 0, //当前回复时的消息包
        _selectAcion: 0, //当前选中的动作
        _isZimo: false, //是否是自摸
        _isBuOnly: false, //是否只有补
        _eatArr: null,
        _cardItem: null,
        _pengArr: null,
        _buArr: null,
        _gangArr: null,
        _cpgBtnWidth: 0,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad: function () {
        this.mMjCardLayer = new cc.Node;
        this.node.addChild(this.mMjCardLayer, 10);

        this.balance.active = false;
        this.balance.zIndex = 110;

        if (this.btnCancel && this.btnHu) {
            this._cpgBtnWidth = this.btnCancel.node.x - this.btnHu.node.x;
        }


        this.cardSelect.active = false;
        this.cardSelect.zIndex = 11;
        this.btnReady.node.active = false;
        this.cpgBar.active = false;
        this.cpgBar.zIndex = 100;
        if (this.waitNode != null) {
            for (var i = 0; i < this.gameFace.length; i++) {
                var head = this.waitNode.getChildByName('head' + (i + 1));
                if (head) {
                    this.gameFace[i].setWaitPos(cc.pAdd(this.waitNode.getPosition(), head.getPosition()));
                    head.removeFromParent();
                }
            }
        }

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, function (event) {
            if (this.balance.active) {
                if (this.balance.getChildByName('HuInfoNode').active) {
                    if (event.keyCode == TVKey.enter || event.keyCode == cc.KEY.enter) {
                        this.onViewClick(null, 'huinfoback');
                    }
                } else {
                    this.balance.getComponent('KeyControl').onKeyPressed(event.keyCode);
                }
            } else if (this.cpgBar.active) {
                this.cpgBar.getComponent('KeyControl').onKeyPressed(event.keyCode);
            } else if (this.waitNode.active) {
                this.getComponent('KeyControl').onKeyPressed(event.keyCode);
            } else if (this._selectCard != null || this._tableState == TABLESTATE.tsPlaying || this._tableState == TABLESTATE.tsStart) {
                //选牌的动作 
                if (this._selectIdx == -1) {
                    this._selectIdx = tool.PlayerManager().m_MySelf.m_cardSpriteList.length - 1;
                } else if (event.keyCode == cc.KEY.right || event.keyCode == TVKey.right) {
                    this._selectIdx++;
                    if (this._selectIdx >= tool.PlayerManager().m_MySelf.m_cardSpriteList.length) {
                        this._selectIdx = 0;
                    }
                } else if (event.keyCode == cc.KEY.left || event.keyCode == TVKey.left) {
                    this._selectIdx--;
                    if (this._selectIdx < 0) {
                        this._selectIdx = tool.PlayerManager().m_MySelf.m_cardSpriteList.length - 1;
                    }

                    if (this._selectCard && cc.isValid(this._selectCard.node)) {
                        this._selectCard.setChecked(false);
                    }
                } else if (event.keyCode == cc.KEY.enter || event.keyCode == TVKey.enter) {

                    if (tool.PlayerManager().m_MySelf.m_nCardNums == 10) {
                        tool.PlayerManager().m_MySelf.getFunction('getCard').call(tool.PlayerManager().m_MySelf, 11);
                    } else {
                        tool.PlayerManager().m_MySelf.outCard(this._selectCard.getCard());
                    }

                    // NetManager.sendPacketForever(MJPACKET.CSOUTCARD, (PlayerManager.m_MySelf.m_nOutCount << 6) + card);

                    // tool.PlayerManager().m_MySelf.setGetCard();

                    return;
                }
                if (this._selectCard && cc.isValid(this._selectCard.node)) {
                    this._selectCard.setChecked(false);
                }

                this._selectCard = tool.PlayerManager().m_MySelf.m_cardSpriteList[this._selectIdx];
                this._selectCard.setChecked(true);
                this.cardSelect.setPosition(this._selectCard.node.getPosition());
                this.cardSelect.x += 5;
                this.cardSelect.y -= 8;
                this.cardSelect.active = true;
            }
        }, this);



    },



    loadGameHander: function () {
        if (this._packetload)
            return;
        this._packetload = true;
        tool.NetManager().addGameHandler('SCRULE', function (data, isRecord) {
            this.setGameInfo(data);
        }, this);

        tool.NetManager().addGameHandler('GAMESTART', function (data, isRecord) {
            if (data.turnId == 1) {
                if (cc.director.getScene().getName() != tool.NetManager().getGameScene().toLocaleLowerCase()) {
                    cc.director.loadScene(tool.NetManager().getGameScene().toLocaleLowerCase(), function () {
                        this.gameStart(data, isRecord);
                    }.bind(this));
                    return;
                }
            }
            this.gameStart(data, isRecord);
        }, this);

        tool.NetManager().addGameHandler('SCRECONNECT', function (data, isRecord) {
            // cc.log('断线重连');
            this.setGameInfo(data);
            this.clearSprite();
            var PlayerManager = tool.PlayerManager();
            this._tableState = data.start;
            // scene.mWBalance.mBirdNums = 0; 
            this.setWaitInfoVisible(true);
            // scene.getChildByName('hint_piaotime').setVisible(false);


            this.gameFace.forEach(function (face) {
                face.node.active = false;
            }.bind(this));

            if (data.player) {
                data.player.forEach(function (pInfo) {
                    var p = PlayerManager.getPlayer(pInfo.id);
                    if (p) {
                        this.gameFace[p.m_nSeadOrd].node.active = true;
                    }
                }.bind(this));
            }

            if (data.state != TABLESTATE.tsWaiting) {
                this.setWaitInfoVisible(false);
                PlayerManager.mPlayerNums = data.player.length;
                this.btnReady.node.active = false;

                var bankerP = PlayerManager.getPlayer(data['bankId']);
                for (var i = 0; i < this.gameFace.length; i++) {
                    this.gameFace[i].setIsBanker(false);
                    this.gameFace[i].setIsReady(false);
                    if (bankerP && bankerP.m_nSeadOrd == i) {
                        this.gameFace[i].setIsBanker(true);
                    }
                }
                this.updatePlayerFace(bankerP);
            }

            switch (data.state) {
                case TABLESTATE.tsWaiting:
                    {
                        for (var i = 0; i < data.player.length; i++) {
                            var pInfo = data.player[i];
                            var p = PlayerManager.getPlayer(pInfo.id);
                            if (p) {
                                p.m_btOffline = pInfo.offline;
                                p.m_boReady = pInfo.ready;
                                this.gameFace[p.m_nSeadOrd].setOffLine(p.m_btOffline);
                                this.gameFace[p.m_nSeadOrd].node.active = true;
                                if (p.m_boReady) {
                                    p.doReady();
                                } else if (p == PlayerManager.m_MySelf) {
                                    this.btnReady.node.active = true;
                                }
                            }
                        }
                    }
                    break;
                case TABLESTATE.tsBalance:
                    {
                        this.setWaitInfoVisible(false);
                        this.updateCardNums(80);
                        tool.NetManager().sendPacket('PLAYERSTART');
                        for (var i = 0; i < data.player.length; i++) {
                            var pInfo = data.player[i];
                            var p = PlayerManager.getPlayer(pInfo.id);
                            if (p) {
                                p.m_btOffline = pInfo.offline;
                                p.m_boReady = pInfo.ready;
                                this.gameFace[p.m_nSeadOrd].node.active = true;
                                this.gameFace[p.m_nSeadOrd].setOffLine(p.m_btOffline);
                                if (p.m_boReady) {
                                    p.doReady();
                                } else if (p == PlayerManager.m_MySelf) {
                                    this.btnReady.node.active = true;;
                                }
                                this.gameFace[p.m_nSeadOrd].setIsReady(p.m_boReady);
                            }
                        }
                    }
                    break;
                case TABLESTATE.tsStart:
                case TABLESTATE.tsPlaying:
                    {
                        this.setWaitInfoVisible(false);
                        var bankerP = PlayerManager.getPlayer(data['bankId']);
                        for (var i = 0; i < 4; i++) {
                            this.gameFace[i].setIsBanker(false);
                            this.gameFace[i].setIsReady(false);
                            if (bankerP && bankerP.m_nSeadOrd == i) {
                                this.gameFace[i].setIsBanker(true);
                            }
                        }

                        this.updateCardNums(data['cards']);

                        // if (scene.mGameConfig.type == GAMETYPE.MAXSCORE) {
                        //     scene.mlbTurns.setString(data['turnId'] + '局');
                        // } else {
                        //     scene.mlbTurns.setString(data['turnId'] + '/' + scene.mGameConfig.turn + '局');
                        // }


                        this._curPlayer = PlayerManager.getPlayer(data.curPlayer);
                        this._lastPlayer = PlayerManager.getPlayer(data.lastPlayerID);
                        this._lastOutCard = data.lastcoutcard;

                        for (var i = 0; i < data.player.length; i++) {
                            var pInfo = data.player[i];
                            var p = PlayerManager.getPlayer(pInfo.id);
                            if (p == null)
                                continue;
                            p.gameStart();
                            p.m_point = pInfo.point;
                            p.m_gold = pInfo.gold;
                            p.m_btOffline = pInfo.offline;
                            p.mPiao = pInfo.piao;
                            if (p.m_nSeadOrd >= 0 && p.m_nSeadOrd <= 3) {
                                this.gameFace[p.m_nSeadOrd].setOffLine(p.m_btOffline);
                                this.gameFace[p.m_nSeadOrd].setGold(p.m_point);
                                if (p.mPiao >= 0) {
                                    this.gameFace[p.m_nSeadOrd].setPiao(p.mPiao);
                                }
                            }

                            if (pInfo.handcard && pInfo.handcard.length > 0) {
                                for (var l = 0; l < pInfo.handcard.length; l++) {
                                    p.m_nCards[l] = pInfo.handcard[l];
                                }
                                p.m_nCardNums = pInfo.handcard.length;
                                p.m_boMingPai = true;
                            } else {
                                p.m_nCardNums = pInfo.cardcount;
                            }
                            if (pInfo.outcard == null)
                                p.m_nOutCount = 0;
                            else
                                p.m_nOutCount = pInfo.outcard.length;
                            for (var l = 0; l < p.m_nOutCount; l++) {
                                p.m_nOutCards[l] = pInfo.outcard[l];
                            }

                            p.m_btOffline = pInfo.state;
                            p.m_nCPGCount = 0;
                            if (pInfo.cpg != null)
                                p.m_nCPGCount = pInfo.cpg.length;
                            for (var l = 0; l < p.m_nCPGCount; l++) {
                                p.m_EatCards[l] = pInfo.cpg[l];
                            }

                            p.makeCardSprites();
                            p.makeCPGSprites();
                            p.makeOutSprite();
                        }
                        if (data.lastcoutcard != 0 && this._lastPlayer) {
                            this._lastPlayer.makeOutCard(data.lastcoutcard);
                        }

                        for (var i = 0; i < data.player.length; i++) {
                            var pInfo = data.player[i];
                            var p = PlayerManager.getPlayer(pInfo.id);
                            p.turnOff();
                        }

                        if (this._curPlayer) {
                            if (data.handcard && data.handcard > 0) {
                                this._curPlayer.setGetCard(data.handcard);
                            }
                            this._curPlayer.showTimer(15);
                            this._curPlayer.turnOn(true);
                        }

                    }
                    break;
                case TABLESTATE.tsCallPoint:
                    {
                        this.setWaitInfoVisible(false);
                        for (var i = 0; i < data.player.length; i++) {
                            var pInfo = data.player[i];
                            var p = PlayerManager.getPlayer(pInfo.id);
                            p.gameStart();
                            p.m_point = pInfo.point;
                            p.m_gold = pInfo.gold;
                            p.m_btOffline = pInfo.offline;
                            p.mPiao = pInfo.piao;

                            this.gameFace[p.m_nSeadOrd].setOffLine(p.m_btOffline);
                            this.gameFace[p.m_nSeadOrd].setGold(p.m_point);
                            if (p.mPiao >= 0) {
                                this.gameFace[p.m_nSeadOrd].setPiao(p.mPiao);
                            }
                            if (p == PlayerManager.m_MySelf && data.config.isPiao && p.mPiao == -1 && data.state == TABLESTATE.tsCallPoint) {
                                // this.mCallPointLayout.show(Number.parseInt(UserDataManager.getItem('csmjdefaultpiao', '0')));
                                // this.getChildByName('hint_piaotime').setVisible(true);
                            }
                        }
                    }
                    break;
            }

            // if (data.vote != null && data.vote.by != -1) {
            //     var reqDissmissWin = WindowManager.getWindowById(GameConfig.WINDOW_REQDISMISS);
            //     reqDissmissWin.showByData(data.vote);
            // }

            NetManager.unblock('SCRECONNECT');

        }, this);


        tool.NetManager().addGameHandler('SCPIAO', function (data, isRecord) {

            cc.log('漂分');

        }, this);

        tool.NetManager().addGameHandler('SCRANDOM', function (data, isRecord) {

            cc.log('随机换位');

        }, this);

        tool.NetManager().addGameHandler('SCSTARTHU', function (data, isRecord) {

            cc.log('起手胡');

        }, this);

        tool.NetManager().addGameHandler('SCOUTCARD', function (data, isRecord) {
            var p = tool.PlayerManager().getPlayer(data['id'], isRecord);
            if (p) {
                p.outCard(data['card']);
            }
            NetManager.unblock('SCOUTCARD');

        }, this);

        tool.NetManager().addGameHandler('SCGETCARD', function (data, isRecord) {
            var p = tool.PlayerManager().getPlayer(data['id'], isRecord);
            if (p) {
                p.getFunction('getCard').call(p, data['card']);
            }
            NetManager.unblock('SCGETCARD');
        }, this);

        tool.NetManager().addGameHandler('SCQUESTEAT', function (data, isRecord) {
            if (isRecord) {
                if (data.id != tool.NetManager().mRecordMy_Self) {
                    var p = tool.PlayerManager().getPlayer(data['id'], isRecord);
                    if (p) {
                        p.m_turnCPGNums == 0;
                    }
                    tool.NetManager().next();
                    return;
                }
            }
            if (data == ACTION.none || data.type == ACTION.none) {
                this.cpgBar.active = false;
                if (!isRecord && tool.PlayerManager().m_MySelf) {
                    tool.PlayerManager().m_MySelf.getFunction('showHintHu').call(tool.PlayerManager().m_MySelf);
                }
            } else if (data.type == ACTION.haidi) {
                var p = tool.PlayerManager().getPlayer(data.id, isRecord);
                p.turnOn();
                if (p === tool.PlayerManager().m_MySelf) {
                    this._packetID = data.msid;
                    tool.showMessageBox('是否要海底?', function () {
                        tool.NetManager().sendPacket('CSEAT', {
                            type: ACTION.haidi,
                            msid: this._packetID
                        });
                    }.bind(this), function () {
                        tool.NetManager().sendPacket('CSEAT', {
                            type: ACTION.none,
                            msid: this._packetID
                        });
                    }.bind(this));
                }
            } else {
                this.onShowCPGSelect(data);
            }
        }, this);

        tool.NetManager().addGameHandler('SCEAT', function (data, isRecord) {
            cc.log('吃碰杠');
            var p = tool.PlayerManager().getPlayer(data['id'], isRecord);
            if (p) {
                p.getFunction('CPG').call(p, data['card']);
            }
            NetManager.unblock('SCEAT');
        }, this);

        tool.NetManager().addGameHandler('SCCALLHU', function (data, isRecord) {

            var p = tool.PlayerManager().getPlayer(data['id'], isRecord);
            if (p) {
                p.getFunction('callHu').call(p, data);
            }
            NetManager.block(1);
            if (isRecord) {
                NetManager.nextTime(1);
            }

        }, this);

        tool.NetManager().addGameHandler('SHOWHAIDICARD', function (data, isRecord) {

            cc.log('SHOWHAIDICARD');

        }, this);

        tool.NetManager().addGameHandler('SCBIRD', function (data, isRecord) {

            cc.log('SCBIRD');

        }, this);

        tool.NetManager().addGameHandler('SCSHOWCARDS', function (data, isRecord) {

            cc.log('SCSHOWCARDS');

        }, this);

        tool.NetManager().addGameHandler('SCBALANCE', function (data, isRecord) {
            cc.log('SCBALANCE');
            cc.log('data:' + JSON.stringify(data));
            this._tableState = TABLESTATE.tsBalance;
            this.balance.getChildByName('btn_showhuinfo').active = false;
            this.balance.getChildByName('HuInfoNode').active = false;
            var huinfo = this.balance.getChildByName('HuInfoNode');
            for (var i = 0; i < 4; i++) {
                huinfo.getChildByName('node' + (i + 1)).active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('icon_huflag').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('icon_starthuflag').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('img_bird1').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('img_bird2').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('img_bird3').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('img_bird4').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbBird1').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbBird2').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbBird3').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbBird4').active = false;
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbStartHu1').getComponent(cc.Label).string = '';
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbStartHu2').getComponent(cc.Label).string = '';
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbStartHu3').getComponent(cc.Label).string = '';
                huinfo.getChildByName('node' + (i + 1)).getChildByName('lbStartHu4').getComponent(cc.Label).string = '';
            }

            this.balance.getComponent('GameBalance').setIsGameOver(false);
            this.balance.getComponent('GameBalance').gameOver(data, isRecord);
            NetManager.unblock('SCBALANCE');
        }, this);

        tool.NetManager().addGameHandler('SCGAMEOVER', function (data, isRecord) {

            cc.log('SCGAMEOVER');

        }, this);
    },

    /**
     * 清空全部精灵
     */
    clearTouchSpriteList: function () {

    },

    setHintVisible: function (visible) {

    },

    updatePlayerFace(banker) {
        var PlayerManager = tool.PlayerManager();
        if (PlayerManager.mPlayerNums == 3) {
            var p = PlayerManager.getPlayerBySead(2);
            if (p) {
                if (PlayerManager.getPlayerBySead(3)) {
                    p.m_nSeadOrd = 1;
                    this.gameFace[2].node.active = false;
                    this.gameFace[1].setPlayer(p);
                    this.gameFace[1].setPiao(p.mPiao);
                } else {
                    p.m_nSeadOrd = 3;
                    this.gameFace[2].node.active = false;
                    this.gameFace[3].setPlayer(p);
                    this.gameFace[3].setPiao(p.mPiao);
                    if (banker && banker.m_chrID == p.m_chrID) {
                        this.gameFace[3].setIsBanker(true);
                    }
                }
            }
        } else if (PlayerManager.mPlayerNums == 2) {
            var p = PlayerManager.getPlayerBySead(1);
            if (p) {
                p.m_nSeadOrd = 2;
                this.gameFace[1].node.active = false;
                this.gameFace[2].setPlayer(p);
                this.gameFace[2].setPiao(p.mPiao);
                if (banker && banker.m_chrID == p.m_chrID) {
                    this.gameFace[2].setIsBanker(true);
                }
            } else {
                p = PlayerManager.getPlayerBySead(3);
                if (p) {
                    p.m_nSeadOrd = 2;
                    this.gameFace[3].node.active = false;
                    this.gameFace[2].setPlayer(p);
                    this.gameFace[2].setPiao(p.mPiao);
                    if (banker && banker.m_chrID == p.m_chrID) {
                        this.gameFace[2].setIsBanker(true);
                    }
                }
            }
        }
    },

    getData: function (name, data) {

    },

    start: function () {
        this.loadGameHander();
        tool.NetManager().unblock('SCENTERTABLE');
        this.cpgBar.active = false;
        this.gameFace.forEach(face => {
            face.waitForStart();
            face.node.active = false;
        });
        this.setWaitInfoVisible(false);

        if (tool.NetManager().mIsPlayRecord) {
            for (var i = 0; i < tool.PlayerManager().m_RecordPlayer.length; i++) {
                if (!tool.PlayerManager().m_RecordPlayer[i].mIsFree) {
                    var player = tool.PlayerManager().m_RecordPlayer[i];
                    if (player.m_nSeadOrd >= 0 && player.m_nSeadOrd < this.gameFace.length) {
                        this.gameFace[player.m_nSeadOrd].node.active = true;
                        this.gameFace[player.m_nSeadOrd].setPlayer(player);
                    }
                }
            }
        } else {
            for (var i = 0; i < tool.PlayerManager().m_GamePlayer.length; i++) {
                if (!tool.PlayerManager().m_GamePlayer[i].mIsFree) {
                    var player = tool.PlayerManager().m_GamePlayer[i];
                    if (player.m_nSeadOrd >= 0 && player.m_nSeadOrd < this.gameFace.length) {
                        this.gameFace[player.m_nSeadOrd].node.active = true;
                        this.gameFace[player.m_nSeadOrd].setPlayer(player);
                    }
                }
            }
        }






        this._tableState = TABLESTATE.tsPlaying;
        tool.PlayerManager().m_MySelf = tool.PlayerManager().m_GamePlayer[0];
        for (var i = 0; i < 4; i++) {
            var mySelf = tool.PlayerManager().m_GamePlayer[i];
            mySelf.m_showName = '玩家:' + i;
            mySelf.m_chrID = i;
            mySelf.m_nSeadOrd = i;
            mySelf.m_boMingPai = false;
            mySelf.m_boHandDown = false;

            mySelf.setGameAction(new(require('MJAction')));
            mySelf.m_nCPGCount = 2;
            mySelf.m_EatCards[0].type = 3;
            mySelf.m_EatCards[0].card = 1;
            mySelf.m_EatCards[0].first = 1;

            mySelf.m_EatCards[1].type = 3;
            mySelf.m_EatCards[1].card = 1;
            mySelf.m_EatCards[1].first = 1;

            if (i == 0) {
                mySelf.m_boMingPai = true;
            }

            mySelf.m_nCards = [1, 12, 3, 4, 2, 12, 13, 14, 21, 22, 23, 24, 28, 2];
            mySelf.m_nCardNums = mySelf.m_nCards.length - 6;

            mySelf.m_nOutCount = 14;
            mySelf.m_nOutCards = [1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24, 1, 2, 3, 4, 11, 12, 13, 14, 24, 24]

            mySelf.makeCPGSprites();
            mySelf.makeCardSprites(false);
            mySelf.makeOutSprite();
        }

        tool.NetManager().handler('SCBALANCE', {
            "cur": 2,
            "time": 25517065,
            "banker": 2,
            "pao": 1,
            "player": [{
                "id": 0,
                "score": 6,
                "hutype": 0,
                "hufan": 0,
                "starthutype": 256,
                "istop": false,
                "starthuscore": 33312
            }, {
                "id": 1,
                "score": -6,
                "hutype": 0,
                "hufan": 0,
                "starthutype": 0,
                "istop": false,
                "huscore": 262144
            }, {
                "id": 2,
                "score": 0,
                "hutype": 1,
                "hufan": 2,
                "starthutype": 0,
                "istop": false,
                "hucards": [18]
            }]
        }, false);

        // this.balance.getComponent('GameBalance').setIsGameOver(false);
        // this.balance.getComponent('GameBalance').gameOver({
        //     "cur": 2,
        //     "time": 25517065,
        //     "banker": 2,
        //     "pao": 1,
        //     "player": [{
        //         "id": 0,
        //         "score": 6,
        //         "hutype": 0,
        //         "hufan": 0,
        //         "starthutype": 256,
        //         "istop": false,
        //         "starthuscore": 33312
        //     }, {
        //         "id": 1,
        //         "score": -6,
        //         "hutype": 0,
        //         "hufan": 0,
        //         "starthutype": 0,
        //         "istop": false,
        //         "huscore": 262144
        //     }, {
        //         "id": 2,
        //         "score": 0,
        //         "hutype": 1,
        //         "hufan": 2,
        //         "starthutype": 0,
        //         "istop": false,
        //         "hucards": [18]
        //     }]
        // }, false);

        // this.onShowCPGSelect({
        //     "id": 1,
        //     "type": 6,
        //     "msid": 6,
        //     "carditem": [{
        //             "type": 2,
        //             "card": [13, 22]
        //         },
        //         {
        //             "type": 4,
        //             "card": [13, 22, 11]
        //         }
        //     ]
        // })
    },

    getMJFileName: function (card) {
        var faceName = '';
        if (card == 35) {
            faceName = "mj_zhong";
        } else {
            var point = card % 10;
            switch (Number.parseInt(card / 10)) {
                case 0:
                    {
                        faceName = 'mj_wan' + point;
                    }
                    break;
                case 1:
                    {
                        faceName = 'mj_tiao' + point;
                    }
                    break;
                case 2:
                    {
                        faceName = 'mj_tong' + point;
                    }
                    break;
                default:
                    faceName = "";
                    break;
            }
        }
        return faceName;
    },


    onShowBox: function (action) {
        this._selectAcion = action;
        tool.NetManager().sendPacket('CSEAT', {
            type: action,
            msid: this._packetID
        });
        // this.mSelectAction = action;
        // this.getChildByName('lbTitle').y = 100;
        // if (action == ACTION.chi) {
        //     if(this._eatArr.length <= 1){
        //         tool.NetManager().sendPacket('CSEAT',{
        //             type: ACTION.chi,
        //             msid: this._packetID
        //         })
        //     }else{

        //     }
        //     if (this.mEatArr.length <= 1) {
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.chi,
        //             msid: this.m_packetID
        //         });

        //     } else {
        //         this.getChildByName('lbTitle').setVisible(true)
        //         this.getChildByName('btnNode').setVisible(false);
        //         if (this.mEatCardArr.length <= 1) {
        //             var idx = 0;
        //             for (var l = 0; l < this.mEatArr.length; l++) {
        //                 this.m_boxEat[idx].removeChildByTag(1111);
        //                 var node = new cc.Node();
        //                 node.setTag(1111);
        //                 this.m_boxEat[idx].addChild(node);
        //                 this.m_boxEat[idx].setVisible(true);
        //                 this.m_boxEat[idx].setName(((this.mEatArr[l].first << 8) + this.mEatArr[l].card + ''));
        //                 this.createCPGBox(node, EATCARDTYPE.ectShun, this.mEatArr[l].first, this.mEatArr[l].card);
        //                 idx++;
        //             }
        //         } else {
        //             var topH = 1;
        //             for (var i = 0; i < this.mEatCardArr.length; i++) {
        //                 var ecard = this.mEatCardArr[i];
        //                 var idx = 0;
        //                 for (var l = 0; l < this.mEatArr.length; l++) {
        //                     if (this.mEatArr[l].card == ecard) {
        //                         this.m_boxEat[i + idx * 4].removeChildByTag(1111);
        //                         var node = new cc.Node();
        //                         node.setTag(1111);
        //                         this.m_boxEat[i + idx * 4].addChild(node);
        //                         this.m_boxEat[i + idx * 4].setVisible(true);
        //                         this.m_boxEat[i + idx * 4].setName(((this.mEatArr[l].first << 8) + this.mEatArr[l].card + ''));
        //                         this.createCPGBox(node, EATCARDTYPE.ectShun, this.mEatArr[l].first, this.mEatArr[l].card);
        //                         idx++;
        //                         if (idx > topH) {
        //                             topH = idx;
        //                         }
        //                     }
        //                 }
        //             }
        //             this.getChildByName('lbTitle').y = 100 * topH;
        //         }

        //     }
        // } else if (action == ACTION.peng) {
        //     if (this.mPengArr.length <= 1) {
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.peng,
        //             msid: this.m_packetID,
        //             card: this.mPengArr[0]
        //         });
        //     } else {
        //         this.getChildByName('lbTitle').setVisible(true)
        //         this.getChildByName('btnNode').setVisible(false);
        //         for (var i = 0; i < this.mPengArr.length; i++) {
        //             this.m_boxEat[i].removeChildByTag(1111);
        //             var node = new cc.Node();
        //             node.setTag(1111);
        //             this.m_boxEat[i].addChild(node);
        //             this.m_boxEat[i].setVisible(true);
        //             this.m_boxEat[i].setName((this.mPengArr[i] + ''));
        //             this.createCPGBox(node, EATCARDTYPE.ectPeng, this.mPengArr[i], this.mPengArr[i]);
        //         }
        //     }
        // } else if (action == ACTION.bu) {
        //     if (this.mBuArr.length <= 1) {
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.bu,
        //             msid: this.m_packetID,
        //             card: this.mBuArr[0]
        //         });
        //     } else {
        //         this.getChildByName('lbTitle').setVisible(true)
        //         this.getChildByName('btnNode').setVisible(false);
        //         for (var i = 0; i < this.mBuArr.length; i++) {
        //             this.m_boxEat[i].removeChildByTag(1111);
        //             var node = new cc.Node();
        //             node.setTag(1111);
        //             this.m_boxEat[i].addChild(node);
        //             this.m_boxEat[i].setVisible(true);
        //             this.m_boxEat[i].setName((this.mBuArr[i] + ''));
        //             this.createCPGBox(node, EATCARDTYPE.ectGang, this.mBuArr[i], this.mBuArr[i]);
        //         }
        //     }
        // } else if (action == ACTION.gang) {
        //     if (this.mGangArr.length <= 1) {
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.gang,
        //             msid: this.m_packetID,
        //             card: this.mGangArr[0]
        //         });
        //     } else {
        //         this.getChildByName('lbTitle').setVisible(true)
        //         this.getChildByName('btnNode').setVisible(false);
        //         for (var i = 0; i < this.mGangArr.length; i++) {
        //             this.m_boxEat[i].removeChildByTag(1111);
        //             var node = new cc.Node();
        //             node.setTag(1111);
        //             this.m_boxEat[i].addChild(node);
        //             this.m_boxEat[i].setVisible(true);
        //             this.m_boxEat[i].setName((this.mGangArr[i] + ''));
        //             this.createCPGBox(node, EATCARDTYPE.ectGang, this.mGangArr[i], this.mGangArr[i]);
        //         }
        //     }
        // }
    },

    showBtnCardInfo: function (btn, info, action) {
        // //找到不同的牌
        for (var i = 0; i < 7; i++) {
            btn.node.getChildByName("card" + (i + 1)).active = false;
        }

        var cardArr = [];
        if (action != ACTION.chi) {
            for (var i = 0; i < info.length; i++) {
                if (info[i].type != action)
                    continue;
                if (info[i].card.length == 1)
                    cardArr.push(info[i].card[0]);
                else {
                    cardArr = info[i].card;
                }
            }
            if (cardArr.length == 0) {
                cardArr.push(this.m_lastOutCard);
            }
        } else {
            if (info == null || info.length == 0) {
                cardArr.push(this.m_lastOutCard);
            } else {
                for (var i = 0; i < info.length; i++) {
                    if (info[i].card && cardArr.indexOf(info[i].card) == -1) {
                        cardArr.push(info[i].card);
                    }
                }
            }
        }




        if (cardArr.length == 1) {
            btn.node.getChildByName("card1").active = true;
            btn.node.getChildByName("card1").getComponent(cc.Sprite).spriteFrame = this.MJTexturePlist.getSpriteFrame(this.getMJFileName(cardArr[0]));
        } else if (cardArr.length == 2) {
            btn.node.getChildByName("card2").active = true;
            btn.node.getChildByName("card3").active = true;
            btn.node.getChildByName("card2").getComponent(cc.Sprite).spriteFrame = this.MJTexturePlist.getSpriteFrame(this.getMJFileName(cardArr[0]));
            btn.node.getChildByName("card3").getComponent(cc.Sprite).spriteFrame = this.MJTexturePlist.getSpriteFrame(this.getMJFileName(cardArr[1]));
        } else if (cardArr.length == 3) {
            for (var i = 0; i < 3; i++) {
                btn.node.getChildByName("card" + (4 + i)).active = true;
                btn.node.getChildByName("card" + (4 + i)).getComponent(cc.Sprite).spriteFrame = this.MJTexturePlist.getSpriteFrame(this.getMJFileName(cardArr[i]));
            }
        } else if (cardArr.length == 4) {
            for (var i = 0; i < 4; i++) {
                btn.node.getChildByName("card" + (4 + i)).active = true;
                btn.node.getChildByName("card" + (4 + i)).getComponent(cc.Sprite).spriteFrame = this.MJTexturePlist.getSpriteFrame(this.getMJFileName(cardArr[i]));
            }
        }


        switch (action) {
            case ACTION.chi:
                this._eatArr = cardArr;
                btn.spriteFrame = this.chiSprArr[cardArr.length - 1];
                break;
            case ACTION.peng:
                this._pengArr = cardArr;
                btn.spriteFrame = this.pengSprArr[cardArr.length - 1];
                break;
            case ACTION.bu:
                this._buArr = cardArr;
                btn.spriteFrame = this.buSprArr[cardArr.length - 1];
                break;
            case ACTION.gang:
                this._gangArr = cardArr;
                btn.spriteFrame = this.gangSprArr[cardArr.length - 1];
                break;
        }
        var myself = tool.PlayerManager().m_MySelf;

        if (action == ACTION.bu) {
            for (var i = 0; i < cardArr.length; i++) {
                if (myself && cardArr[i] == myself.m_getCard) {
                    return false;
                }
            }
            return true;
        }
        return false;
    },

    onShowCPGSelect: function (info) {



        this._hutype = ACTION.node;
        this._packetID == info.msid;
        // this.getChildByName('lbTitle').setVisible(false)

        this._isZimo = false;
        this._isBuOnly = false;
        this._selectAcion = ACTION.node;
        this.cpgBar.active = true;

        this._eatArr = info.eatarr;
        this._cardItem = info.carditem;

        this.btnCancel.node.active = true;
        if (this.btnChi) this.btnChi.node.active = false;
        if (this.btnPeng) this.btnPeng.node.active = false;
        if (this.btnGang) this.btnGang.node.active = false;
        if (this.btnBu) this.btnBu.node.active = false;
        if (this.btnHu) this.btnHu.node.active = false;
        if (this.btnZimo) this.btnZimo.node.active = false;


        this._pengArr = []; //碰的列表
        this._buArr = []; //补的列表
        this._gangArr = []; //杠的列表


        this.boxEat.forEach(element => {
            element.active = false;
        });

        var isBu = info.type & ACTION.bu;
        var isGang = info.type & ACTION.gang;
        var isPeng = info.type & ACTION.peng;
        var isEat = info.type & ACTION.chi;
        var isHu = info.type & (ACTION.hu | ACTION.starthu | ACTION.midhu);

        if (isHu > 0) {
            this._hutype = ACTION.hu;
            if ((info.type & ACTION.starthu) == ACTION.starthu) {
                this._hutype = ACTION.starthu;
                isBu = false;
                isGang = false;
            } else if ((info.type & ACTION.midhu == ACTION.midhu)) {
                this._hutype = ACTION.midhu;
                isBu = false;
                isGang = false;
            }
        }

        var btnNum = 1;

        if (this.tingNode && this.tingNode.active) {
            this.tingNode.setOpacity(50);
        }

        if (isHu) {
            this.btnHu.node.active = true;
            this.btnZimo.node.active = false;
            if (tool.PlayerManager().m_MySelf == this._curPlayer) {
                this.btnHu.node.active = false;
                this.btnZimo.node.active = true;
            }
            btnNum++;
        }

        if (isEat) {
            this.btnChi.node.active = true;
            this.btnChi.node.x = this.btnCancel.node.x - this._cpgBtnWidth * btnNum;
            this.showBtnCardInfo(this.btnChi, info.eatarr, ACTION.chi);
            btnNum++;
        }

        if (isPeng) {
            this.btnPeng.node.active = true;
            this.btnPeng.node.x = this.btnCancel.node.x - this._cpgBtnWidth * btnNum;
            this.showBtnCardInfo(this.btnPeng, info.carditem, ACTION.peng);
            btnNum++;
        }

        if (isBu) {
            this.btnBu.node.active = true;
            this.btnBu.node.x = this.btnCancel.node.x - this._cpgBtnWidth * btnNum;
            this._isBuOnly = this.showBtnCardInfo(this.btnBu, info.carditem, ACTION.bu);
            if (this._buArr.length > 1)
                this._isBuOnly = false;
            btnNum++;
        }

        if (isGang) {
            this.btnGang.node.active = true;
            this.btnGang.node.x = this.btnCancel.node.x - this._cpgBtnWidth * btnNum;
            this.showBtnCardInfo(this.btnGang, info.carditem, ACTION.gang);
            btnNum++;
        }

    },

    updateCardNums: function () {

    },

    setWaitInfoVisible: function (isWait) {
        this.waitNode.active = isWait;
        this.btnExit.node.active = isWait;
        // this.getChildByName('node_rule').setVisible(!isVisible);
        // this.mlbWaitRoomID.setVisible(isVisible);
        // this.mlbWiatRule.setVisible(isVisible);
        // this.getChildByName('btn_Invite').setVisible(isVisible);
        // this.getChildByName('chk_quick').setSelected(false);
        // if (cc.sys.isNative && !cc.Application.getInstance().isWXAppInstalled()) {
        //     this.getChildByName('btn_Invite').setVisible(false)
        // }
        // this.mlbTurns.setVisible(!isVisible);
        // this.mlbCardNums.setVisible(!isVisible);
        // // if (isVisible) {
        // //     this.mClock.hide();
        // // } else {
        // //     this.mClock.showWithRing();
        // // }

        // this.getChildByName('img_center').setVisible(isVisible);
        // this.getChildByName('btn_backroom').setVisible(isVisible);
        // this.getChildByName('btn_giveuproom').setVisible(isVisible);
        // this.getChildByName('btn_copyroominfo').setVisible(false);
        // this.getChildByName('btn_exitgame').setVisible(false);


        for (var i = 0; i < this.gameFace.length; i++) {
            if (isWait) {
                this.gameFace[i].waitForStart();
            } else {
                this.gameFace[i].moveToGamePos(false);
            }
        }

        // this.getChildByName('chk_quick').setVisible(false);

        // if (isVisible) {
        //     this.getChildByName('chk_quick').setTouchEnabled(true);
        // }

        // if (PlayerManager.m_MySelf == null)
        //     return;
        // if (isVisible) {
        //     if (this.mMatchID != 0) {
        //         if (this.mIsShowQuick) {
        //             if (PlayerManager.m_MySelf.mQuick) {
        //                 this.getChildByName('chk_quick').setVisible(true);
        //                 this.getChildByName('chk_quick').setSelected(true);
        //             } else if (PlayerManager.m_GamePlayer.length < 4) {
        //                 this.getChildByName('chk_quick').setVisible(true);
        //                 this.getChildByName('chk_quick').setSelected(false);
        //             }
        //         }

        //         this.getChildByName('chk_quick').setVisible(true);
        //         this.getChildByName('btn_giveuproom').setVisible(false);
        //         this.getChildByName('btn_exitgame').setVisible(true);
        //     } else if (this.mMakerID != PlayerManager.m_MySelf.m_dbid) {
        //         this.getChildByName('btn_giveuproom').setVisible(true);
        //         this.getChildByName('btn_exitgame').setVisible(false);
        //     }

        // }
    },

    initWithPlayer: function (player) {
        cc.log('initWithPlayer');
    },

    clearTouchSpriteList: function () {

    },

    setGameInfo: function (info) {
        this._gameConfig = info.config;
        this._roomID = info.tid;

        this._makerID = Number.parseInt(info.maker);
        this._makerID = Number.parseInt(info.matchid);
        this.roomLable.string = '房号:' + info.tid;
        this.ruleLable.string = '';

        // this.mlbTurns.setString('1/' + info.config.turn + '局');
        // this.mWBalance.setMatchInfo(false);
        // this.mWGameResult.setMatchInfo(false);
        // this.mWGameResult.setGameInfo(info);
        // this.getChildByName('chk_quick').setVisible(false);
        // this.mIsShowQuick = false;


        var ruleStr = tool.getMJConfig(this._gameConfig, true);
        ruleStr = info.config.turn + '局 ' + ruleStr;
        this.ruleLable.string = ruleStr;

        // if (info.config.gametype == MJGAMETYPE.CSMJ) {
        //     this.getChildByName('icongame').loadTexture('icon_game1_0.png', MjSpriteManager.mFileType);
        // } else if (info.config.gametype == MJGAMETYPE.ZZMJ) {
        //     this.getChildByName('icongame').loadTexture('icon_game1_1.png', MjSpriteManager.mFileType);
        // } else if (info.config.gametype == MJGAMETYPE.HZMJ) {
        //     this.getChildByName('icongame').loadTexture('icon_game1_2.png', MjSpriteManager.mFileType);
        // } else if (info.config.gametype == MJGAMETYPE.TDH) {
        //     this.getChildByName('icongame').loadTexture('icon_game1_3.png', MjSpriteManager.mFileType);
        // }


        // this.m_wCPGBar.mIsCSMJ = false;
        // MjSpriteManager.mNeedJiang = false;
        // if (info.config.gametype == MJGAMETYPE.CSMJ) {
        //     this.m_wCPGBar.mIsCSMJ = true;
        //     MjSpriteManager.mNeedJiang = true;
        //     if (CheckWordFlag(info.config.hutype, CREATEHUTYPE.luanjianhu)) {
        //         MjSpriteManager.mNeedJiang = false;
        //     }
        // }
        // if (info.config.type == GAMETYPE.MAXSCORE) {
        //     this.mlbTurns.setString('1' + '局');
        // } else {
        //     this.mlbTurns.setString('1/' + this._gameConfig.turn + '局');
        // }

        if (tool.PlayerManager().m_MySelf) {
            tool.PlayerManager().m_MySelf.setGameConfig(info.config);
        }


        // var ruleStr = MjSpriteManager.getConfig(this._gameConfig);
        // if (this._makerID != 0) {
        //     //是公会比赛
        //     var matchInfo = getMatchById(this._makerID);
        //     if (matchInfo != null) {
        //         this.mlbRoomID.setString(matchInfo.name);
        //         this.mlbWaitRoomID.setString(matchInfo.name);
        //         this.mWBalance.setMatchInfo(true, matchInfo.name);
        //         this.mWGameResult.setMatchInfo(true, matchInfo.name);
        //         this.mMatchRoomName = matchInfo.name;
        //     }
        //     this.mIsShowQuick = true
        //     if (this._gameConfig.playnums == 2) {
        //         this.mIsShowQuick = false;
        //     }
        //     if (this.mIsShowQuick)
        //         this.getChildByName('chk_quick').setVisible(true);
        // }

        // this.mRule.getChildByName('lbrule').setString(ruleStr);
        // if (this.mRule.getChildByName('lbrule').height <= 100) {
        //     this.mRule.height = 110;
        // } else {
        //     this.mRule.height = this.mRule.getChildByName('lbrule').height;
        // }
        // this.mRule.y = this.mRulePos.y;
        // this.mRule.getChildByName('lbrule').y = this.mRule.height / 2 - 10;
        // this.mRoomNewPos.y = this.mRoomOldPos.y - this.mRule.height + 20;


        // if (this.mlbRoomID.y != this.mRoomOldPos.y) {
        //     this.mlbRoomID.y = this.mRoomNewPos.y;
        // }
    },

    clearSprite: function () {

    },

    showStartAnim: function () {

    },

    gameStart: function (data, isRecord) {
        // playEffect('start');
        // playEffect('start');
        this.cardSelect.active = false;
        // scene.getChildByName('hint_piaotime').setVisible(false);
        // scene.getChildByName('btn_ready').setVisible(false);
        this.btnReady.active = false;
        this._tableState = TABLESTATE.tsStart;
        // scene.getChildByName('hint_piaotime').setVisible(false); 
        //     scene.mWBalance.mBirdNums = 0; 
        this._bankerID = data.bankId;
        this._gangPlayer = null;

        var PlayerManager = tool.PlayerManager();
        var bankerP = PlayerManager.getPlayer(this._bankerID, isRecord);

        for (var i = 0; i < this.gameFace.length; i++) {
            this.gameFace[i].setIsBanker(false);
            this.gameFace[i].setIsReady(false);
            if (bankerP && bankerP.m_nSeadOrd == i) {
                this.gameFace[i].setIsBanker(true);
            }
        }

        this.updatePlayerFace(bankerP);

        // if(this._gameConfig.type == GAMETYPE.MAXSCORE){

        // }else{

        // }
        //     if (scene.mGameConfig.type == GAMETYPE.MAXSCORE) {
        //         scene.mlbTurns.setString(data['turnId'] + '局');
        //     } else {
        //         scene.mlbTurns.setString(data['turnId'] + '/' + scene.mGameConfig.turn + '局');
        //     }

        this.updateCardNums(data['cards']);
        this.setWaitInfoVisible(false);

        // PlayerManager.m_GamePlayer.forEach(function (p) {
        //     if (p && !p.mIsFree) {
        //         p.gameStart();
        //     }
        // }.bind(this));



        //     this.updateCardNums(data['cards']);
        //     scene.mWBalance.setVisible(false);
        //     this.setWaitInfoVisible(false);


        data.player.forEach(element => {
            var p = PlayerManager.getPlayer(element['id'], isRecord);
            if (p) {
                p.gameStart();
                if (element.handcard) {
                    for (var i = 0; i < element['handcard'].length; i++) {
                        p.m_nCards[i] = element['handcard'][i];
                        p.m_nCardNums = element['handcard'].length;
                        p.m_boMingPai = true;
                    }
                    if (isRecord)
                        p.m_boHandDown = true;
                } else {
                    p.m_nCardNums = 13;
                }
                p.m_gold = element['gold'];
                p.m_point = element['point'];
                p.turnOff();
                if (p == bankerP) {
                    p.m_nCardNums = 14;
                    bankerP.turnOn();
                }

                p.makeCardSprites();
                if (!isRecord) {
                    p.m_btOffline = data['state'];
                    this.gameFace[p.m_nSeadOrd].setOffLine(p.m_btOffline);
                }

                p.turnOff();
            }
        });


        if (data.turn <= 1) {
            NetManager.block(1);
            scene.showStartAnim();
        } else {
            tool.NetManager().unblock('GAMESTART');
        }

    },


    showBalanceItem: function (node, p, idx, item, result) {

        // var item = result.player[i];
        // var pao = result.pao;

        var playIdr = [];
        for (var i = 0; i < result.player.length; i++) {
            playIdr.push(result.player[i].id);
        }

        node.getChildByName('bird1').active = false;
        node.getChildByName('bird2').active = false;
        node.getChildByName('lbbird1').active = false;
        node.getChildByName('lbbird2').active = false;
        node.getChildByName('bg').active = false;
        node.getChildByName('icon_banker').active = false;
        // node.getChildByName('iconhu').active = false;
        node.getChildByName('name').getComponent(cc.Label).string = '';
        node.getChildByName('gold').getComponent(cc.Label).string = '';
        // node.getChildByName('gold').active = false;
        node.getChildByName('img_maxpoint').active = item.istop;
        // node.getChildByName('icon_baopei').active = false;

        node.getChildByName('icon_zpao').active = false;
        node.getChildByName('icon_pao').active = false;
        node.getChildByName('icon_zimo').active = false;

        node.getChildByName('icon').active = false;
        node.getChildByName('card1').active = false;
        node.getChildByName('card2').active = false;
        node.getChildByName('card3').active = false;
        node.getChildByName('card4').active = false;
        node.getChildByName('card5').active = false;
        node.getChildByName('card6').active = false;

        if (p == null)
            return;
        p.m_point += item.score;
        if (p == tool.PlayerManager().m_MySelf) {
            node.getChildByName('bg').active = true;
        }
        if (p.m_chrID == result.banker) {
            node.getChildByName('icon_banker').active = true;
        }
        // if (result.peiId != null && p.m_chrID == result.peiId) {
        //     node.getChildByName('icon_baopei').setVisible(true);
        // }


        node.getChildByName('name').getComponent(cc.Label).string = p.m_showName;
        if (item.score >= 0) {
            node.getChildByName('gold').getComponent(cc.Label).string = '+' + item.score;
        } else {
            node.getChildByName('gold').getComponent(cc.Label).string = item.score;
        }

        // if (p.m_birdNums > 0) {
        //     var getBird = 0; //中鸟数
        //     var noBird = 0; //没中的鸟数
        //     for (var l = 0; l < this.mBirdArr.length; l++) {
        //         if (this.mBirdArr[l].id == p.m_chrID) {
        //             if (this.mBirdArr[l].hit) {
        //                 getBird++;
        //             } else {
        //                 noBird++;
        //             }
        //         }
        //     }

        //     if (getBird + noBird <= 2) {
        //         for (var i = 0; i < getBird; i++) {
        //             var mBird = node.getChildByName('bird1');
        //             if (mBird.isVisible()) {
        //                 mBird = node.getChildByName('bird2');
        //             }
        //             mBird.setVisible(true);
        //             mBird.loadTexture('img_birdzhong.png', MjSpriteManager.mFileType);
        //         }
        //         for (var i = 0; i < noBird; i++) {
        //             var mBird = node.getChildByName('bird1');
        //             if (mBird.isVisible()) {
        //                 mBird = node.getChildByName('bird2');
        //             }
        //             mBird.setVisible(true);
        //             mBird.loadTexture('img_birdno.png', MjSpriteManager.mFileType);

        //         }
        //     } else {
        //         //有多个鸟
        //         if (getBird > 0) {
        //             var mBird = node.getChildByName('bird1');
        //             mBird.loadTexture('img_birdzhong.png', MjSpriteManager.mFileType);
        //             mBird.setVisible(true);

        //             //相应的数字
        //             if (getBird > 1) {
        //                 node.getChildByName('lbNiao1').setString('+' + getBird);
        //                 node.getChildByName('lbNiao1').setVisible(true);
        //             }
        //         }

        //         if (noBird > 0) {
        //             var mBird = node.getChildByName('bird1');
        //             if (mBird.isVisible()) {
        //                 mBird = node.getChildByName('bird2');
        //             }
        //             mBird.loadTexture('img_birdno.png', MjSpriteManager.mFileType);
        //             mBird.setVisible(true);

        //             var lbBird = node.getChildByName('lbNiao1');
        //             if (lbBird.isVisible()) {
        //                 lbBird = node.getChildByName('lbNiao2');
        //             }
        //             lbBird.setVisible(true);
        //             if (noBird > 1) {
        //                 lbBird.setString('+' + noBird);
        //             }
        //         }
        //     }
        // }

        // var isHu = false;
        // if (item.hutype != null && item.hutype != HUTYPE.none) {
        //     isHu = true;
        //     this.mIsHangZhuang = false;
        // }
        // if (this.mIsShowGangScore) {
        //     this.getMjGangInfo(node, p.mPiao, item.hutype, p.m_nCPGCount, p.m_EatCards);
        // } else {
        //     this.createHuType(node, p.mPiao, item.starthutype, item.hutype, pao != -1, item.hucards ? item.hucards.length : 0);
        // }


        if (item.hucards && item.hucards.length) {
            if (result.pao != -1) {
                node.getChildByName('icon_zpao').active = true;
            } else if ((item.hutype & HUTYPE.zimohu) == HUTYPE.zimohu || (item.hutype & HUTYPE.tianhu) == HUTYPE.tianhu) {
                node.getChildByName('icon_zimo').active = true;
            }
        } else if (p.m_chrID == result.pao) {
            node.getChildByName('icon_zpao').active = false;
            node.getChildByName('icon_pao').active = true;
            node.getChildByName('icon_zimo').active = false;
        }




        // if (item.hufan > 0) {
        //     node.getChildByName('lbFan').setVisible(true);
        //     node.getChildByName('lbFan').setString(item.hufan + '番');
        // }

        // if (item.score >= 0) {
        //     node.getChildByName('lbGold').setString('+' + item.score);
        // } else {
        //     node.getChildByName('lbGold').setString(item.score);
        // } 
        // this.showHuInfo(item.id, item.huscore, pao, result.player);
        // this.showStartHuInfo(item.id, item.starthuscore, result.player);



        // var huPos1 = node.getChildByName("mj3").getPosition();
        // var huPos2 = node.getChildByName("mj4").getPosition();
        // var huPos3 = node.getChildByName("mj5").getPosition();
        // var huPos4 = node.getChildByName("mj6").getPosition();

        var mjItem = node.getChildByName('nodeMj');
        if (mjItem) {
            mjItem.removeAllChildren();
        } else {
            mjItem = new cc.Node();
            mjItem.setName('nodeMj');
            node.addChild(mjItem);
        }

        var startPos = node.getChildByName('card1').getPosition();
        var fixPos = node.getChildByName('card2').getPosition();
        var scale = node.getChildByName('card1').getScale();
        fixPos = cc.pSub(fixPos, startPos);
        for (var i = 0; i < p.m_nCPGCount; i++) {
            var cardInfoArr = [-1, -1, -1, -1];
            MJTool.createCpgItem(cardInfoArr, p.m_EatCards[i]);

            for (var l = 0; l < 4; l++) {
                if (cardInfoArr[i] == -1) {
                    break;
                }
                var mjBj = cc.instantiate(this.MJSprite);
                mjBj.getComponent('MJCardSprite').init(cardInfoArr[i], 0, this.MJCARD[0], CardSpriteType.cstCPG);
                if (l == 3) {
                    mjBj.setPosition(cc.pAdd(startPos, fixPos));
                    mjBj.y += 16;
                } else {
                    mjBj.setPosition(cc.pAdd(startPos, cc.pMult(fixPos, l)));
                }
                mjBj.setScale(scale);
                mjItem.addChild(mjBj);
            }
            startPos.x += (10 + 3 * fixPos.x);
        }


        var huIdx = -1;
        if (item.hucards && item.hucards.length > 0) {
            //有多个 
            huIdx = p.m_nCardNums - 1;
            if (p.m_nCardNums + 3 * p.m_nCPGCount == 14) {
                var idx = item.hucards.indexOf(p.m_nCards[p.m_nCardNums - 1]);
                if (idx >= 0) {
                    for (var i = 0; i < item.hucards.length; i++) {
                        if (i == idx) {
                            continue;
                        }
                        p.m_nCards[p.m_nCardNums++] = item.hucards[i];
                    }
                } else {
                    //反向查找
                    var lIdx = 0;
                    for (var i = 0; i < item.hucards.length; i++) {
                        lIdx = i;
                        var idx = p.m_nCards.indexOf(item.hucards[i]);
                        if (idx >= 0) {
                            p.m_nCards[idx] = p.m_nCards[p.m_nCardNums - 1];
                            p.m_nCards[p.m_nCardNums - 1] = item.hucards[i];
                            break;
                        }
                    }
                    for (var i = 0; i < item.hucards.length; i++) {
                        if (i != lIdx) {
                            p.m_nCards[p.m_nCardNums++] = item.hucards[i];
                        }
                    }

                }
            } else {
                huIdx = p.m_nCardNums;
                for (var i = 0; i < item.hucards.length; i++) {
                    p.m_nCards[p.m_nCardNums++] = item.hucards[i];
                }
            }
        } else if (this.mIsHangZhuang && ((p.m_nCardNums + 3 * p.m_nCPGCount) == 14) && haidi > 0) {
            //判断海底牌
            huIdx = p.m_nCards.indexOf(haidi);
            if (huIdx >= 0) {
                p.m_nCards[huIdx] = p.m_nCards[p.m_nCardNums - 1];
                p.m_nCards[p.m_nCardNums - 1] = haidi;
                huIdx = p.m_nCardNums - 1;
            }
        }


        for (var i = 0; i < p.m_nCardNums; i++) {
            var mjBj = cc.instantiate(this.MJSprite);
            mjBj.getComponent('MJCardSprite').init(p.m_nCards[i], 0, this.MJCARD[0], CardSpriteType.cstCPG);
            mjItem.addChild(mjBj);
            mjBj.setScale(scale);
            mjBj.setPosition(startPos);
            startPos.x += fixPos.x;
            if (i >= huIdx && huIdx != -1) {
                if (i == huIdx) {
                    mjBj.setPosition(node.getChildByName("card3").getPosition());
                } else if (i == huIdx + 1) {
                    mjBj.setPosition(node.getChildByName("card4").getPosition());
                } else if (i == huIdx + 2) {
                    mjBj.setPosition(node.getChildByName("card5").getPosition());
                } else if (i == huIdx + 3) {
                    mjBj.setPosition(node.getChildByName("card6").getPosition());
                }
                var icon = new cc.Node();
                var spr = icon.addComponent(cc.Sprite);
                if (this._isHangZhuang) {
                    //海底的，设置一下 
                    spr.spriteFrame = this.cardHaidi;
                    icon.x -= 11;
                    icon.y += 7;
                    mjBj.addChild(icon);
                } else {
                    //胡的。设置一下
                    spr.spriteFrame = this.cardHu;
                    mjItem.addChild(icon);
                    icon.x = mjBj.x + 25;
                    icon.y = mjBj.y + 30;
                }
            }
        }



        var idx = 0;
        var huinfo = item.huscore;
        var myIdx = playIdr.indexOf(item.id);
        var socreArr = [0, 0, 0];
        var myScore = 0;
        // item.id, item.huscore, pao, result.player
        if (huinfo >= 0) {
            this.balance.getChildByName('btn_showhuinfo').active = true;
            var huInfoNode = this.balance.getChildByName('HuInfoNode');
            socreArr = [0, 0, 0];
            //显示具体信息
            socreArr[0] = ((huinfo >> 24) & 0xff);
            socreArr[1] = ((huinfo >> 16) & 0xff);
            socreArr[2] = ((huinfo >> 8) & 0xff);
            myScore = 0;
            if (result.pao != null && result.pao >= 0) {
                socreArr[0] = -socreArr[0];
                socreArr[1] = -socreArr[1];
                socreArr[2] = -socreArr[2];

                for (var i = 0; i < playIdr.length; i++) {
                    if (playIdr[i] == item.id)
                        continue;
                    if (socreArr[idx] != 0) {
                        huInfoNode.getChildByName('node' + (i + 1)).getChildByName('icon_huflag').active = true;
                    }
                    idx++;
                }
            } else {
                huInfoNode.getChildByName('node' + (myIdx + 1)).getChildByName('icon_huflag').active = true;
            }
            myScore = socreArr[0] + socreArr[1] + socreArr[2];
            socreArr.splice(item.id, 0, 0);
            idx = 0;
            for (var i = 0; i < playIdr.length; i++) {
                idx++;
                if (playIdr[i] == item.id) {
                    huInfoNode.getChildByName('node' + idx).getChildByName('lbHuScore').getComponent(cc.Label).string = myScore;
                } else {
                    huInfoNode.getChildByName('node' + idx).getChildByName('lbHuScore').getComponent(cc.Label).string = -socreArr[playIdr[i]];
                }
            }
        }

        huinfo = item.starthuscore;
        if (huinfo == null || huinfo == -1)
            return;
        this.balance.getChildByName('btn_showhuinfo').active = true;

        socreArr = [0, 0, 0];
        //显示具体信息
        myScore = 0;
        var score4 = (huinfo >> 27);
        socreArr[0] = (huinfo & 0x01ff);
        socreArr[1] = ((huinfo >> 9) & 0x01ff);
        socreArr[2] = ((huinfo >> 18) & 0x01ff);
        myScore = (socreArr[0] >> 4) + (socreArr[1] >> 4) + (socreArr[2] >> 4);

        socreArr.splice(item.id, 0, 0);

        //有鸟
        var huInfoNode = this.balance.getChildByName('HuInfoNode');
        huInfoNode.getChildByName('node' + (myIdx + 1)).active = true;
        huInfoNode.getChildByName('node' + (myIdx + 1)).getChildByName('icon_starthuflag').active = true;
        if (score4 > 0) {
            huInfoNode.getChildByName('node' + (myIdx + 1)).getChildByName('img_bird' + (myIdx + 1)).active = true;
            huInfoNode.getChildByName('node' + (myIdx + 1)).getChildByName('lbBird' + (myIdx + 1)).active = true;
            huInfoNode.getChildByName('node' + (myIdx + 1)).getChildByName('lbBird' + (myIdx + 1)).getComponent(cc.Label).string = '+' + score4;
        }
        huInfoNode.getChildByName('node' + (myIdx + 1)).getChildByName('lbStartHu' + (myIdx + 1)).getComponent(cc.Label).string = '+' + myScore;

        idx = 0;
        for (var i = 0; i < playIdr.length; i++) {
            idx++;
            if (playIdr[i] == item.id)
                continue;
            huInfoNode.getChildByName('node' + idx).active = true;
            huInfoNode.getChildByName('node' + (idx)).getChildByName('lbStartHu' + (myIdx + 1)).getComponent(cc.Label).string = ('-' + (socreArr[playIdr[i]] >> 4));
            var birdNums = (socreArr[playIdr[i]] & 0x0f);
            if (birdNums > 0) {
                huInfoNode.getChildByName('node' + (idx)).getChildByName('img_bird' + (myIdx + 1)).active = true;
                huInfoNode.getChildByName('node' + (idx)).getChildByName('lbBird' + (myIdx + 1)).active = true;
                huInfoNode.getChildByName('node' + (idx)).getChildByName('lbBird' + (myIdx + 1)).getComponent(cc.Label).string = ('+' + birdNums);
            }
        }

    },



    onViewClick: function (sender, data) {
        cc.log(' data = ' + data);
        switch (data) {
            case 'giveuproom':
                NetManager.sendPacket('CSDESTORY');
                break;
            case 'showhuinfo':
                {
                    this.balance.getChildByName('HuInfoNode').active = true;
                    this.balance.getChildByName('btn_showhuinfo').getComponent('KeyView').clearFocuse();
                }
                break;
            case 'huinfoback': //隐藏胡的信息
                {
                    this.balance.getChildByName('HuInfoNode').active = false;
                    this.balance.getChildByName('btn_showhuinfo').getComponent('KeyView').onFocuse();
                    this.balance.getChildByName('btn_enter').getComponent('KeyView').clearFocuse();
                    // this.balance.getChildByName('btn_showhuinfo').getComponent('KeyView').clearFocuse();
                }
                break;
            case 'cancel': //取消了吃碰杠
                {
                    if (this._hutype == ACTION.hu && this._isZimo) {
                        //能自摸
                        tool.showMessageBoxWithCancel('是否放弃自摸？', function () {
                            //取消动作
                            tool.NetManager().sendPacket('CSEAT', {
                                type: ACTION.none,
                                msid: this._packetID
                            });
                        }.bind(this));
                    } else if (this.mHuType == ACTION.midhu) {
                        //中途胡
                        //能自摸
                        tool.showMessageBoxWithCancel('是否放弃中途胡？', function () {
                            //取消动作
                            tool.NetManager().sendPacket('CSEAT', {
                                type: ACTION.none,
                                msid: this._packetID
                            });
                        }.bind(this));
                    } else if (this.mHuType == ACTION.starthu) {
                        //能自摸
                        tool.showMessageBoxWithCancel('是否放弃起手胡？', function () {
                            //取消动作
                            tool.NetManager().sendPacket('CSEAT', {
                                type: ACTION.none,
                                msid: this._packetID
                            });
                        }.bind(this));
                    } else {
                        //取消动作
                        tool.NetManager().sendPacket('CSEAT', {
                            type: ACTION.none,
                            msid: this._packetID
                        });
                    }
                }
                break;
            case 'peng': //碰
                this.onShowBox(ACTION.peng);
                break;
            case 'gang': //杠
                this.onShowBox(ACTION.gang);
                break;
            case 'bu': //补
                this.onShowBox(ACTION.bu);
                break;
            case 'hu': //胡
                this.onShowBox(ACTION.bu);
                break;
            case 'zimo': //自摸
                this.onShowBox(ACTION.bu);
                break;
        }

        // var id = btn.getTag();
        // if (id >= 1000) {
        //     this.onEatBoxClick(id - 1000, btn.getName());
        // } else if (id == ACTION.none) {

        // if (this.mHuType == ACTION.hu && this.mIsZimo) {
        //     //能自摸
        //     showMessageBoxWithCancel('是否放弃自摸？', function () {
        //         //取消动作
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.none,
        //             msid: this.m_packetID
        //         });
        //     }.bind(this));
        // } else if (this.mHuType == ACTION.midhu) {
        //     //中途胡
        //     //能自摸
        //     showMessageBoxWithCancel('是否放弃中途胡？', function () {
        //         //取消动作
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.none,
        //             msid: this.m_packetID
        //         });
        //     }.bind(this));
        // } else if (this.mHuType == ACTION.starthu) {
        //     //能自摸
        //     showMessageBoxWithCancel('是否放弃起手胡？', function () {
        //         //取消动作
        //         NetManager.sendPacket(MJPACKET.CSEAT, {
        //             type: ACTION.none,
        //             msid: this.m_packetID
        //         });
        //     }.bind(this));
        // } else {
        //     //取消动作
        //     NetManager.sendPacket(MJPACKET.CSEAT, {
        //         type: ACTION.none,
        //         msid: this.m_packetID
        //     });
        // }
        // } else if (id == ACTION.hu) {
        //     //动作胡
        //     NetManager.sendPacket(MJPACKET.CSEAT, {
        //         type: this.mHuType,
        //         msid: this.m_packetID
        //     });
        // } else {
        //     //其它动作
        //     this.onShowBox(id);
        // }
    },

    onKeyBack: function () {

    },

    onKeyMenu: function () {

    }

    // update (dt) {},
});